"""
智能体管理路由
"""

import uuid
from datetime import datetime
from typing import Optional, List, Union, Dict, Any

from fastapi import APIRouter, HTTPException, Depends, Query
from sqlalchemy import and_
from sqlalchemy.orm import Session

from config.database import get_db_session
from constant.settings import settings
from mcp_tools.mcpManager import mcp_manager
from pojo.ai_web_agent import (
    AIWebAgentCreate, AIWebAgentUpdate, AIWebAgentResponse,
    AIWebAgentListResponse, AIWebAgentStatusUpdate, AIWebAgentVersionUpdate
)
from pojo.ai_web_agent_model import AIWebAgentModel
from pojo.ai_web_mcp_tools_model import AIWebMCPToolsModel
from pojo.ai_web_scene_model import AIWebSceneModel

router = APIRouter()


# MCP工具相关辅助函数
def validate_mcp_tools(db: Session, mcp_list: List[Union[str, Dict[str, Any]]]) -> List[str]:
    """验证并提取MCP工具ID列表"""
    mcp_ids = []

    for mcp_item in mcp_list:
        if isinstance(mcp_item, str):
            # 如果是字符串，直接作为MCP ID
            mcp_ids.append(mcp_item)
        elif isinstance(mcp_item, dict):
            # 如果是字典，提取ID字段
            mcp_id = mcp_item.get('id') or mcp_item.get('mcp_id') or mcp_item.get('value')
            if mcp_id:
                mcp_ids.append(mcp_id)

    # 验证MCP工具是否存在且已上线
    valid_mcp_ids = []
    for mcp_id in mcp_ids:
        mcp_tool = db.query(AIWebMCPToolsModel).filter(
            AIWebMCPToolsModel.id == mcp_id,
            AIWebMCPToolsModel.status == 1  # 已上线
        ).first()

        if mcp_tool:
            valid_mcp_ids.append(mcp_id)
        else:
            print(f"警告：MCP工具 {mcp_id} 不存在或未上线，已跳过")

    return valid_mcp_ids


def get_agent_mcp_tools(db: Session, agent_id: str) -> List[Dict[str, Any]]:
    """获取智能体的MCP工具列表"""
    try:
        # 获取智能体信息
        agent = db.query(AIWebAgentModel).filter(
            AIWebAgentModel.agent_id == agent_id,
            AIWebAgentModel.is_deleted == 0
        ).first()

        if not agent:
            return []

        # 获取MCP工具ID列表
        mcp_list = agent.get_mcp_list()
        mcp_ids = validate_mcp_tools(db, mcp_list)

        if not mcp_ids:
            return []

        # 获取MCP工具详情
        return mcp_manager.get_mcp_tools_for_agent(db, mcp_ids)

    except Exception as e:
        print(f"获取智能体MCP工具失败: {e}")
        return []


def get_agent_tools_summary(db: Session, agent_id: str) -> Dict[str, Any]:
    """获取智能体的工具配置摘要"""
    try:
        # 获取智能体信息
        agent = db.query(AIWebAgentModel).filter(
            AIWebAgentModel.agent_id == agent_id,
            AIWebAgentModel.is_deleted == 0
        ).first()

        if not agent:
            return {}

        # 获取基础工具数量
        tools_list = agent.get_tools_list()
        base_tools_count = len(tools_list) if tools_list else 0

        # 获取MCP工具
        mcp_tools = get_agent_mcp_tools(db, agent_id)
        mcp_tools_count = len(mcp_tools)

        # 统计各个MCP工具集的工具数量
        mcp_summary = {}
        for tool in mcp_tools:
            mcp_name = tool.get('mcp_name', 'Unknown')
            if mcp_name not in mcp_summary:
                mcp_summary[mcp_name] = {
                    'mcp_id': tool.get('mcp_id'),
                    'tools_count': 0,
                    'enabled_tools': 0
                }
            mcp_summary[mcp_name]['tools_count'] += 1
            if tool.get('is_enabled'):
                mcp_summary[mcp_name]['enabled_tools'] += 1

        return {
            'base_tools_count': base_tools_count,
            'mcp_tools_count': mcp_tools_count,
            'total_tools_count': base_tools_count + mcp_tools_count,
            'mcp_summary': mcp_summary
        }

    except Exception as e:
        print(f"获取智能体工具摘要失败: {e}")
        return {}


@router.get("/", response_model=AIWebAgentListResponse)
async def get_agents(
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        scene_id: Optional[str] = Query(None, description="所属场景ID"),
        tenant_id: Optional[str] = Query(None, description="租户ID"),
        agent_name: Optional[str] = Query(None, description="智能体名称模糊查询"),
        status: Optional[int] = Query(None, description="状态筛选"),
        llm_code: Optional[str] = Query(None, description="大模型代码筛选"),
        created_by: Optional[str] = Query(None, description="创建者筛选"),
        is_deleted: int = Query(0, description="删除标记：0-未删除,1-已删除"),
        db: Session = Depends(get_db_session)
):
    """获取智能体列表"""
    try:
        # 构建查询条件
        query = db.query(AIWebAgentModel).filter(AIWebAgentModel.is_deleted == is_deleted)

        if scene_id:
            query = query.filter(AIWebAgentModel.scene_id == scene_id)
        if tenant_id:
            query = query.filter(AIWebAgentModel.tenant_id == tenant_id)
        if agent_name:
            query = query.filter(AIWebAgentModel.agent_name.like(f"%{agent_name}%"))
        if status is not None:
            # 验证status值
            if status not in [0, 1, 2]:
                raise HTTPException(status_code=400, detail=f"无效的状态值: {status}，必须是 0, 1, 2 中的一个")
            query = query.filter(AIWebAgentModel.status == status)
        if llm_code:
            query = query.filter(AIWebAgentModel.llm_code == llm_code)
        if created_by:
            query = query.filter(AIWebAgentModel.created_by == created_by)

        # 获取总数
        total = query.count()

        # 分页查询
        offset = (page - 1) * page_size
        agents = query.offset(offset).limit(page_size).all()

        # 转换为响应模型
        items = []
        for agent in agents:
            agent_dict = agent.to_dict()
            items.append(AIWebAgentResponse(**agent_dict))

        return AIWebAgentListResponse(total=total, items=items)

    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取智能体列表失败: {str(e)}")


@router.post("/", response_model=AIWebAgentResponse)
async def create_agent(agent: AIWebAgentCreate, db: Session = Depends(get_db_session)):
    """创建智能体"""
    try:
        # 验证场景是否存在
        scene = db.query(AIWebSceneModel).filter(AIWebSceneModel.scene_id == agent.scene_id).first()
        if not scene:
            raise HTTPException(status_code=404, detail="指定的场景不存在")

        # 检查同一场景下智能体名称是否重复
        existing_agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.scene_id == agent.scene_id,
                AIWebAgentModel.agent_name == agent.agent_name,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()
        if existing_agent:
            raise HTTPException(status_code=400, detail="同一场景下智能体名称不能重复")

        # 验证status值（Pydantic已经验证过，这里是额外保险）
        if agent.status not in [0, 1, 2]:
            raise HTTPException(status_code=400, detail=f"无效的状态值: {agent.status}，必须是 0, 1, 2 中的一个")

        # 验证MCP工具
        valid_mcp_ids = []
        if agent.mcp_list:
            valid_mcp_ids = validate_mcp_tools(db, agent.mcp_list)
            if len(valid_mcp_ids) != len(agent.mcp_list):
                print(f"警告：部分MCP工具无效，原始数量: {len(agent.mcp_list)}, 有效数量: {len(valid_mcp_ids)}")

        # 创建智能体
        agent_id = str(uuid.uuid4())
        db_agent = AIWebAgentModel(
            agent_id=agent_id,
            scene_id=agent.scene_id,
            tenant_id=agent.tenant_id,
            agent_code=agent.agent_code,
            agent_name=agent.agent_name,
            sys_prompt=agent.sys_prompt,
            llm_code=agent.llm_code,
            embedding_code=agent.embedding_code,
            status=agent.status,
            version=agent.version,
            created_by=agent.created_by,
            created_at=datetime.now()
        )

        # 设置JSON字段
        db_agent.set_tools_list(agent.tools_list)
        db_agent.set_mcp_list(valid_mcp_ids)  # 使用验证后的MCP ID列表
        db_agent.set_rag_list(agent.rag_list)

        db.add(db_agent)
        db.commit()
        db.refresh(db_agent)

        # 返回创建的智能体
        agent_dict = db_agent.to_dict()
        return AIWebAgentResponse(**agent_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"创建智能体失败: {str(e)}")


@router.get("/{agent_id}", response_model=AIWebAgentResponse)
async def get_agent(agent_id: str, db: Session = Depends(get_db_session)):
    """获取单个智能体详情"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        agent_dict = agent.to_dict()
        return AIWebAgentResponse(**agent_dict)

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取智能体详情失败: {str(e)}")


@router.put("/{agent_id}", response_model=AIWebAgentResponse)
async def update_agent(agent_id: str, agent: AIWebAgentUpdate, db: Session = Depends(get_db_session)):
    """更新智能体"""
    try:
        # 查找智能体
        db_agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not db_agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 检查智能体名称是否重复（如果更新了名称）
        if agent.agent_name and agent.agent_name != db_agent.agent_name:
            existing_agent = db.query(AIWebAgentModel).filter(
                and_(
                    AIWebAgentModel.scene_id == db_agent.scene_id,
                    AIWebAgentModel.agent_name == agent.agent_name,
                    AIWebAgentModel.agent_id != agent_id,
                    AIWebAgentModel.is_deleted == 0
                )
            ).first()
            if existing_agent:
                raise HTTPException(status_code=400, detail="同一场景下智能体名称不能重复")

        # 更新字段
        update_data = agent.model_dump(exclude_unset=True, exclude={'updated_by'})
        for field, value in update_data.items():
            if field == 'tools_list':
                db_agent.set_tools_list(value)
            elif field == 'mcp_list':
                # 验证MCP工具
                if value is not None:
                    valid_mcp_ids = validate_mcp_tools(db, value)
                    if len(valid_mcp_ids) != len(value):
                        print(f"警告：部分MCP工具无效，原始数量: {len(value)}, 有效数量: {len(valid_mcp_ids)}")
                    db_agent.set_mcp_list(valid_mcp_ids)
                else:
                    db_agent.set_mcp_list([])
            elif field == 'rag_list':
                db_agent.set_rag_list(value)
            elif field == 'status':
                # 验证status值（Pydantic已经验证过，这里是额外保险）
                if value not in [0, 1, 2]:
                    raise HTTPException(status_code=400, detail=f"无效的状态值: {value}，必须是 0, 1, 2 中的一个")
                setattr(db_agent, field, value)
            else:
                setattr(db_agent, field, value)

        # 设置更新信息
        db_agent.updated_by = agent.updated_by
        db_agent.updated_at = datetime.now()

        db.commit()
        db.refresh(db_agent)

        agent_dict = db_agent.to_dict()
        return AIWebAgentResponse(**agent_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新智能体失败: {str(e)}")


@router.delete("/{agent_id}")
async def delete_agent(agent_id: str, deleted_by: str = Query(..., description="删除者"),
                       db: Session = Depends(get_db_session)):
    """删除智能体（软删除）"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 软删除
        agent.soft_delete(deleted_by)
        db.commit()

        return {"message": f"智能体 {agent_id} 删除成功"}

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"删除智能体失败: {str(e)}")


@router.post("/{agent_id}/restore")
async def restore_agent(agent_id: str, restored_by: str = Query(..., description="恢复者"),
                        db: Session = Depends(get_db_session)):
    """恢复已删除的智能体"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 1
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="已删除的智能体不存在")

        # 检查恢复后名称是否重复
        existing_agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.scene_id == agent.scene_id,
                AIWebAgentModel.agent_name == agent.agent_name,
                AIWebAgentModel.agent_id != agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()
        if existing_agent:
            raise HTTPException(status_code=400, detail="恢复失败：同一场景下已存在同名智能体")

        # 恢复
        agent.restore(restored_by)
        db.commit()

        return {"message": f"智能体 {agent_id} 恢复成功"}

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"恢复智能体失败: {str(e)}")


@router.patch("/{agent_id}/status", response_model=AIWebAgentResponse)
async def update_agent_status(agent_id: str, status_update: AIWebAgentStatusUpdate,
                              db: Session = Depends(get_db_session)):
    """更新智能体状态"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 更新状态
        agent.update_status(status_update.status, status_update.updated_by)
        db.commit()
        db.refresh(agent)

        agent_dict = agent.to_dict()
        return AIWebAgentResponse(**agent_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新智能体状态失败: {str(e)}")


@router.patch("/{agent_id}/version", response_model=AIWebAgentResponse)
async def update_agent_version(agent_id: str, version_update: AIWebAgentVersionUpdate,
                               db: Session = Depends(get_db_session)):
    """更新智能体版本"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 更新版本
        agent.update_version(version_update.version, version_update.updated_by)
        db.commit()
        db.refresh(agent)

        agent_dict = agent.to_dict()
        return AIWebAgentResponse(**agent_dict)

    except HTTPException:
        raise
    except ValueError as e:
        raise HTTPException(status_code=400, detail=str(e))
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"更新智能体版本失败: {str(e)}")


@router.post("/{agent_id}/clone", response_model=AIWebAgentResponse)
async def clone_agent(
        agent_id: str,
        new_agent_name: str = Query(..., description="新智能体名称"),
        created_by: str = Query(..., description="创建者"),
        db: Session = Depends(get_db_session)
):
    """克隆智能体"""
    try:
        # 查找原智能体
        original_agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not original_agent:
            raise HTTPException(status_code=404, detail="原智能体不存在")

        # 检查新名称是否重复
        existing_agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.scene_id == original_agent.scene_id,
                AIWebAgentModel.agent_name == new_agent_name,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()
        if existing_agent:
            raise HTTPException(status_code=400, detail="同一场景下智能体名称不能重复")

        # 克隆配置
        config = original_agent.clone_config()

        # 验证MCP工具（克隆时重新验证MCP工具的有效性）
        mcp_list = config.get('mcp_list', [])
        valid_mcp_ids = []
        if mcp_list:
            valid_mcp_ids = validate_mcp_tools(db, mcp_list)
            if len(valid_mcp_ids) != len(mcp_list):
                print(f"克隆时MCP工具验证：原始数量: {len(mcp_list)}, 有效数量: {len(valid_mcp_ids)}")

        # 创建新智能体
        new_agent_id = str(uuid.uuid4())
        new_agent = AIWebAgentModel(
            agent_id=new_agent_id,
            scene_id=original_agent.scene_id,
            tenant_id=original_agent.tenant_id,
            agent_name=new_agent_name,
            agent_code=config['agent_code'],
            sys_prompt=config['sys_prompt'],
            llm_code=config['llm_code'],
            embedding_code=config['embedding_code'],
            status=0,  # 克隆的智能体默认为停用状态
            version="1.0.0",  # 重置版本号
            created_by=created_by,
            created_at=datetime.now()
        )

        # 设置JSON字段
        new_agent.set_tools_list(config['tools_list'])
        new_agent.set_mcp_list(valid_mcp_ids)  # 使用验证后的MCP工具列表
        new_agent.set_rag_list(config['rag_list'])

        db.add(new_agent)
        db.commit()
        db.refresh(new_agent)

        agent_dict = new_agent.to_dict()
        return AIWebAgentResponse(**agent_dict)

    except HTTPException:
        raise
    except Exception as e:
        db.rollback()
        raise HTTPException(status_code=500, detail=f"克隆智能体失败: {str(e)}")


@router.get("/{agent_id}/config")
async def get_agent_config(agent_id: str, db: Session = Depends(get_db_session)):
    """获取智能体配置摘要"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 获取基础配置摘要
        base_config = agent.get_config_summary()

        # 获取工具配置摘要
        tools_summary = get_agent_tools_summary(db, agent_id)

        # 合并配置信息
        config_summary = {
            **base_config,
            **tools_summary
        }

        return config_summary

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取智能体配置失败: {str(e)}")


@router.get("/{agent_id}/mcp-tools")
async def get_agent_mcp_tools_list(agent_id: str, db: Session = Depends(get_db_session)):
    """获取智能体的MCP工具列表"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 获取MCP工具列表
        mcp_tools = get_agent_mcp_tools(db, agent_id)

        return {
            "agent_id": agent_id,
            "agent_name": agent.agent_name,
            "mcp_tools_count": len(mcp_tools),
            "mcp_tools": mcp_tools
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取智能体MCP工具列表失败: {str(e)}")


@router.post("/{agent_id}/validate-mcp-tools")
async def validate_agent_mcp_tools(agent_id: str, db: Session = Depends(get_db_session)):
    """验证智能体的MCP工具可用性"""
    try:
        agent = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.agent_id == agent_id,
                AIWebAgentModel.is_deleted == 0
            )
        ).first()

        if not agent:
            raise HTTPException(status_code=404, detail="智能体不存在")

        # 获取MCP工具ID列表
        mcp_list = agent.get_mcp_list()
        mcp_ids = validate_mcp_tools(db, mcp_list)

        # 验证MCP工具的可用性
        validation_results = await mcp_manager.validate_mcp_tools(db, mcp_ids)

        # 统计结果
        total_mcp_count = len(mcp_ids)
        available_count = sum(1 for result in validation_results.values() if result)

        return {
            "agent_id": agent_id,
            "agent_name": agent.agent_name,
            "total_mcp_count": total_mcp_count,
            "available_count": available_count,
            "validation_results": validation_results
        }

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"验证智能体MCP工具失败: {str(e)}")


@router.get("/scene/{scene_id}", response_model=AIWebAgentListResponse)
async def get_agents_by_scene(
        scene_id: str,
        page: int = Query(1, ge=1, description="页码"),
        page_size: int = Query(10, ge=1, le=100, description="每页数量"),
        status: Optional[int] = Query(None, description="状态筛选"),
        db: Session = Depends(get_db_session)
):
    """根据场景ID获取智能体列表"""
    try:
        # 验证场景是否存在
        scene = db.query(AIWebSceneModel).filter(AIWebSceneModel.scene_id == scene_id).first()
        if not scene:
            # 如果指定的场景不存在，使用默认场景ID
            scene_id = settings.DEFAULT_SCENE_ID

        # 构建查询
        query = db.query(AIWebAgentModel).filter(
            and_(
                AIWebAgentModel.scene_id == scene_id,
                AIWebAgentModel.is_deleted == 0
            )
        )

        if status is not None:
            # 验证status值
            if status not in [0, 1, 2]:
                raise HTTPException(status_code=400, detail=f"无效的状态值: {status}，必须是 0, 1, 2 中的一个")
            query = query.filter(AIWebAgentModel.status == status)

        # 获取总数
        total = query.count()

        # 分页查询
        offset = (page - 1) * page_size
        agents = query.offset(offset).limit(page_size).all()

        # 如果查询结果为空，则通过DEFAULT_AGENT_ID查询默认的Agent对象
        if not agents:
            default_agent = db.query(AIWebAgentModel).filter(
                and_(
                    AIWebAgentModel.agent_id == settings.DEFAULT_AGENT_ID,
                    AIWebAgentModel.is_deleted == 0
                )
            ).first()

            if default_agent:
                agents = [default_agent]
                total = 1

        # 转换为响应模型
        items = []
        for agent in agents:
            agent_dict = agent.to_dict()
            items.append(AIWebAgentResponse(**agent_dict))

        return AIWebAgentListResponse(total=total, items=items)

    except HTTPException:
        raise
    except Exception as e:
        raise HTTPException(status_code=500, detail=f"获取场景智能体列表失败: {str(e)}")
